package com.lm.langchain4j.service;

import com.lm.langchain4j.adapter.EmbeddingModelAdapter;
import com.lm.langchain4j.adapter.InMemoryVectorStore;
import dev.langchain4j.model.embedding.EmbeddingModel;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

@Service
public class DocumentService {

    private final EmbeddingModelAdapter embedAdapter;
    private final InMemoryVectorStore vectorStore;

    public DocumentService(EmbeddingModel embeddingModel /*注入langchain4j embedding model bean*/, InMemoryVectorStore vectorStore) {
        this.embedAdapter = new EmbeddingModelAdapter(embeddingModel);
        this.vectorStore = vectorStore;
    }

    /**
     * 简单加载文本文件并切分为固定大小的 chunks（按字符）
     */
    public void loadAndIndex(Path filePath, int chunkSize, int overlap) throws IOException {
        String content = Files.readString(filePath);
        List<String> chunks = chunkText(content, chunkSize, overlap);
        // 批量向量化（按 chunk 顺序）
        List<double[]> vectors = embedAdapter.embedTexts(chunks);
        for (int i = 0; i < chunks.size(); i++) {
            vectorStore.add(vectors.get(i), chunks.get(i));
        }
    }

    private List<String> chunkText(String text, int chunkSize, int overlap) {
        List<String> list = new ArrayList<>();
        int pos = 0;
        while (pos < text.length()) {
            int end = Math.min(pos + chunkSize, text.length());
            list.add(text.substring(pos, end));
            pos = Math.max(end - overlap, end);
        }
        return list;
    }
}
